package com.changgou.order.controller;

import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.CartService;
import com.changgou.order.service.OrderService;
import entity.Result;
import entity.StatusCode;
import entity.TokenDecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/cart")
public class CartController {
    @Autowired
    private CartService cartService;
    /**
     * 加入购物车
     * 1，加入购物车数量
     * 2，商品ID
     */
    @GetMapping(value = "/add")
    public Result add(Integer num , Long id,String username){
        //1,获取用户信息
        Map<String, String> userInfo = TokenDecode.getUserInfo();
        //2，获取用户名， 然后去查询用户名对应的在redis购物车内容
        String username2 = userInfo.get("username");

        cartService.add(num,id,username2);
        return new Result(true, StatusCode.OK,"加入购物车成功");
    }

    @GetMapping(value = "/list")
    public Result<List<OrderItem>> list(){


        //用户的令牌信息-》解析令牌信息-》username
        //用这个对象从令牌中拿用户名
        //Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
       /* //1,从里面拿到全部数据
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication();
        //2,拿到令牌信息
        String tokenValue = details.getTokenValue();
        //3,解析令牌，拿到用户名
        Map<String, String> map = TokenDecode.dcodeToken(tokenValue);
        String username = map.get("username");*/
       // String username = "szitheima";

        //上面的我现在都封装为工具类，因为不一定就一个服务需要

        //1,获取用户信息
        Map<String, String> userInfo = TokenDecode.getUserInfo();
        //2，获取用户名， 然后去查询用户名对应的在redis购物车内容
        String username = userInfo.get("username");

        List<OrderItem> orderItems = cartService.list(username);
        return new Result<List<OrderItem>>(true,StatusCode.OK,"列表查询成功",orderItems);
    }
}
